package com.qili.service.ela.impl;

import com.qili.base.service.impl.BaseServiceImpl;
import com.qili.entity.search.BaseGreenRole;
import com.qili.service.ela.ElasticSerachService;
import com.qili.service.search.BaseGreenRoleService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author zhaoyongke
 * @date 2021/10/7
 * @description
 */
@Service
public class ElasticSerachServiceImpl implements ElasticSerachService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

//        @Autowired
//        private ElkConfig elkConfig;

    /**
     * 根据布尔条件进行查询
     *
     * @param boolQueryBuilder
     * @return
     */
    @Override
    public SearchResponse searchMessage(BoolQueryBuilder boolQueryBuilder, String orderFiled, String start, String size) {
        try {
            SearchRequest searchRequest = new SearchRequest("swordaa");
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.trackTotalHits(true);
            // 分頁开始位置
            if (StringUtils.isNotBlank(start)) {
                sourceBuilder.from(Integer.valueOf(start));
            } else {
                sourceBuilder.from(0);
            }
            if (StringUtils.isNotBlank(size)) {
                // 查询总数量的时候 不设置 size 设置size 太影响效率
                sourceBuilder.size(Integer.valueOf(size));
            } else {
                // 设置返回的数据
                sourceBuilder.size(10);
            }
            sourceBuilder.query(boolQueryBuilder);
            if (StringUtils.isNotBlank(orderFiled)) {
                sourceBuilder.sort(orderFiled, SortOrder.DESC);
            }
            // 分页大于10000 只返回10000
            searchRequest.source(sourceBuilder);

            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//                searchResponse.getHits().forEach(message -> {
//                    try {
//                        String sourceAsString = message.getSourceAsString();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                });
            return searchResponse;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Couldn't get Detail");
        }
    }

    /**
     * 单条件检索
     *
     * @param fieldKey
     * @param fieldValue
     * @return
     */
    @Override
    public MatchPhraseQueryBuilder uniqueMatchQuery(String fieldKey, String fieldValue) {
        MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery(fieldKey, fieldValue);
        return matchPhraseQueryBuilder;
    }

    public QueryBuilder queryId(String fieldValue) {
        QueryBuilder QueryBuilder = QueryBuilders.idsQuery().addIds(fieldValue);
        return QueryBuilder;
    }


    /**
     * 多条件检索并集，适用于搜索比如包含腾讯大王卡，滴滴大王卡的用户
     *
     * @param fieldKey
     * @param queryList
     * @return
     */
    @Override
    public BoolQueryBuilder orMatchUnionWithList(String fieldKey, List<String> queryList) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        for (String fieldValue : queryList) {
            boolQueryBuilder.should(QueryBuilders.matchPhraseQuery(fieldKey, fieldValue));
        }
        return boolQueryBuilder;
    }

    /**
     * 范围查询，左右都是闭集
     *
     * @param fieldKey
     * @param start
     * @param end
     * @return
     */
    @Override
    public RangeQueryBuilder rangeMathQuery(String fieldKey, String start, String end) {
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(fieldKey);
        if (StringUtils.isNotBlank(start)) {
            rangeQueryBuilder.gte(start);
        }
        if (StringUtils.isNotBlank(end)) {
            rangeQueryBuilder.lte(end);
        }
        return rangeQueryBuilder;
    }

    /**
     * 根据中文分词进行查询
     *
     * @param fieldKey
     * @param fieldValue
     * @return
     */
    @Override
    public MatchQueryBuilder matchQueryBuilder(String fieldKey, String fieldValue) {
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(fieldKey, fieldValue).analyzer("ik_smart");
        return matchQueryBuilder;
    }
    @Override
    public void deleteById(String iddelete) {
        try {
            DeleteRequest deleteRequest = new DeleteRequest();
            deleteRequest.index("swordaa");
            deleteRequest.id(iddelete);
            restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


}
